﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.IO;
using SignalLab.BaseLibrary;
using System.Windows.Media.Imaging;

namespace SignalLab
{
  public partial class RecordDetails : PhoneApplicationPage
  {
    public RecordDetails()
    {
      InitializeComponent();
      DataContext = VM = new RecordViewModel(App.Manager.CurrentRecord);
      this.Loaded += new RoutedEventHandler(RecordDetails_Loaded);
      this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(RecordDetails_OrientationChanged);
    }


    void RecordDetails_Loaded(object sender, RoutedEventArgs e)
    {
      visualise();
    }


    void RecordDetails_OrientationChanged(object sender, OrientationChangedEventArgs e)
    {
      visualise();
    }

    void visualise()
    {
      int width = (int)((System.Windows.Controls.Border)(imgVisualiser.Parent)).ActualWidth - 2;
      int height = (int)((System.Windows.Controls.Border)(imgVisualiser.Parent)).ActualHeight - 2;

      var bitmap = new WriteableBitmap(width, height);


      ThreadPool.QueueUserWorkItem((obj) =>
      {
        var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
        VisualiserHelper visualiser;


        using (var fs = storage.OpenFile(App.Manager.CurrentRecord, FileMode.Open, FileAccess.Read))
        {
          fs.Seek(WavHelper.HEADER_LENGTH + 4, SeekOrigin.Begin);
          visualiser = new VisualiserHelper(width, height, fs.Length);
          visualiser.Bitmap = bitmap;
          byte[] buffer = new byte[4096];
          int read;
          while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
          {
            visualiser.Write(buffer);
          }
        }

        Dispatcher.BeginInvoke(new Action(() =>
        {
          visualiser.Bitmap.Invalidate();
          imgVisualiser.Source = visualiser.Bitmap;
        }));
      });
    }

    public RecordViewModel VM;

    private void btnDelete_Click(object sender, RoutedEventArgs e)
    {
      var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
      
      var result = MessageBox.Show("Do you really want to delete the record!",((RecordViewModel)DataContext).ApplicationName, MessageBoxButton.OKCancel);
      if (result == MessageBoxResult.OK)
      {
        storage.DeleteFile(((RecordViewModel)DataContext).RecordName);
      }
      NavigationService.GoBack();
      AppManager.Instance.GetRecords();
    }

    private void btnUpload_Click(object sender, RoutedEventArgs e)
    {
      if (VM.IsUploading)
      {
        MessageBox.Show("File is already uploading");
        return;
      }
      var server = SettingsManager.Account.GetItem("server");
      if (server == null || string.IsNullOrEmpty(server.Value))
      {
        var result = MessageBox.Show("You need an server account to upload record.\nDo you want to set new account?", VM.ApplicationName, MessageBoxButton.OKCancel);
        if (result == MessageBoxResult.OK)
        {
          App.Manager.CurrentSetting = SettingsManager.Account;
          NavigationService.Navigate(new Uri("/SettingsEditor.xaml", UriKind.Relative));
          return;
        }
      }
      string uri = string.Format("{0}?filename={1}", server.Value, VM.RecordName);

      var request = (HttpWebRequest)WebRequest.Create(new Uri(uri));
      request.Method = "POST";
      request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
    }

    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
      HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

      // End the operation
      Stream postStream = request.EndGetRequestStream(asynchronousResult);

      var storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

      using (var fs = storage.OpenFile(App.Manager.CurrentRecord, FileMode.Open, FileAccess.Read))
      {
        byte[] buffer = new byte[4096];
        int read;
        while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
        {
          postStream.Write(buffer, 0, read);
        }
      }
      postStream.Close();

      // Start the asynchronous operation to get the response
      request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
      VM.IsUploading = true;

    }


    private void GetResponseCallback(IAsyncResult asynchronousResult)
    {
      HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

      // End the operation
      try
      {
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        Console.WriteLine(responseString);
        // Close the stream object
        streamResponse.Close();
        streamRead.Close();

        // Release the HttpWebResponse
        response.Close();
      }
      catch (Exception ex)
      {
        Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
          MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButton.OK);
          VM.IsUploading = false;
        }));
        return;
      }

      VM.IsUploading = false;

      Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
      {
        MessageBox.Show("Upload completed.");
      }));

    }
  }
}